<template>
	<view class="container">
		<view class="main">
			<view v-if="Object.keys(fileInfo).length" class="file-info">
				<image class="file-img" :src="fileInfo.original_img" mode="aspectFit"></image>
				<text class="file-txt">{{fileInfo.goods_name}}</text>
			</view>
			<view class="item">
				<view class="item-left">
					打印范围
				</view>
				<view class="item-right">
					<picker mode="multiSelector" :range="pageRangeArr" :value="defaultPageRange"
						:disabled="printForm.maxPage === 1" @change="getPrice('pageRange', $event)">
						<view class="item-action item-action__active">
							<text>{{printForm.pageRange || '全部'}}</text>
							<u-icon name="arrow-down" color="#FF9C24" :size="5"></u-icon>
						</view>
					</picker>
				</view>
			</view>
			<view v-if="paperSize.length" class="item">
				<view class="item-left">
					纸型
				</view>
				<view class="item-right">
					<view class="item-action" :class="[printForm.paperSize == item.id && 'item-action__active']"
						v-for="item in paperSize" :key="item.id" @click.stop="getPrice('paperSize', item.id)">
						{{item.name}}
					</view>
				</view>
			</view>
			<view class="item">
				<view class="item-left">
					色彩
				</view>
				<view class="item-right">
					<view class="item-action" :class="[printForm.color == item.id && 'item-action__active']"
						v-for="item in colorList" :key="item.id" @click.stop="getPrice('color', item.id)">
						{{item.name}}
					</view>
				</view>
			</view>
			<view class="item">
				<view class="item-left">
					单双
				</view>
				<view class="item-right">
					<view class="item-action" :class="[printForm.duplex == item.id && 'item-action__active']"
						v-for="item in duplexList" :key="item.id" @click.stop="getPrice('duplex', item.id)">
						{{item.name}}
					</view>
				</view>
			</view>
			<view class="item">
				<view class="item-left">
					纸张
				</view>
				<view class="item-right">
					<view class="item-action" :class="[printForm.paperType == item.id && 'item-action__active']"
						v-for="item in paperType" :key="item.id" @click.stop="getPrice('paperType', item.id)">
						{{item.name}}
					</view>
				</view>
			</view>
			<view class="item">
				<view class="item-left">
					份数
				</view>
				<view class="item-right">
					<NumberBox :value="printForm.num" :async-change="true" @change="getPrice('num', $event)" />
				</view>
			</view>
			<view v-if="bindingList.length" class="item">
				<view class="item-left">
					装订
				</view>
				<view class="item-right">
					<view class="item-action" :class="[printForm.binding == item.id && 'item-action__active']"
						v-for="item in bindingList" :key="item.id" @click.stop="getPrice('binding', item.id)">
						{{item.name}}
					</view>
				</view>
			</view>
			<view v-if="coverTypeList.length" class="item">
				<view class="item-left">
					封面类型
				</view>
				<view class="item-right">
					<view class="item-action" :class="[printForm.cover == item.id && 'item-action__active']"
						v-for="item in coverTypeList" :key="item.id" @click.stop="getPrice('cover', item.id)">
						{{item.name}}
					</view>
				</view>
			</view>
			<view v-if="selectCoverType.color" class="item">
				<view class="item-left">
					封面颜色
				</view>
				<view class="item-right" style="gap: 8rpx;">
					<view class="action-color-box" :class="[printForm.coverColor == item.id && 'action-color-box__active']"
						v-for="item in selectCoverType.colors_all" :key="item.id">
						<view class="item-action-color"
							:class="[(item.color === '#FFF' || item.color === '#FFFFFF') && 'item-action-color__white']"
							:style="{'background': item.color}" @click.stop="getPrice('coverColor', item.id)">
							{{item.name}}
						</view>
					</view>
				</view>
			</view>
			<view v-if="selectCoverType.cover" class="item">
				<view class="item-left">
					封面内容
				</view>
				<view class="item-right">
					<view class="item-action" :class="[printForm.coverContent == item.id && 'item-action__active']"
						v-for="item in selectCoverType.covers_all" :key="item.id" @click.stop="getPrice('coverContent', item.id)">
						{{item.name}}
					</view>
				</view>
			</view>
			<EditCover :mode="coverCtnType" :text="printForm.coverContentText" :url="printForm.coverContentImage"
				:coverUrl="fileInfo.index_image ? pythonUrl + fileInfo.index_image : null" />
		</view>

		<view class=" footer">
			<view class="price">
				价格: <span>￥</span><span class="price-num">{{totalPrice}}</span>
			</view>
			<view class="actions">
				<view v-if="printForm.file" class="preview" @click="handlePreview">
					预览
				</view>
				<view class="confirm" @click="handleSubmit">
					确定
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		PrintApi
	} from '@/api'
	import NumberBox from '../components/NumberBox.vue'
	import EditCover from '../components/EditCover.vue'
	import {
		BASE_URL,
		PYTHON_URL
	} from '@/config/request'
	import {
		previewFile
	} from '@/utils/util'
	export default {
		components: {
			NumberBox,
			EditCover,
		},
		data() {
			return {
				id: 0,
				pythonUrl: PYTHON_URL,
				totalPrice: 0, // 总价
				// 文件详情
				fileInfo: {},
				// 纸张尺寸
				paperSize: [],
				// 打印颜色
				colorList: [{
						id: 1,
						name: '黑色'
					},
					{
						id: 2,
						name: '彩色'
					}
				],
				// 单双面
				duplexList: [{
						id: 1,
						name: '单面'
					},
					{
						id: 2,
						name: '双面'
					}
				],
				// 纸张类型
				paperType: [{
						id: 1,
						name: '普通纸'
					},
					{
						id: 2,
						name: '护眼纸'
					}
				],
				// 装订方式
				bindingList: [],
				// 打印参数表单
				printForm: {
					file: null
				},
				// 页码选择范围
				pageRangeArr: [],
				// 默认选中的页码范围
				defaultPageRange: [],
				// 封面类型列表
				coverTypeList: [],
				// 选中的封面类型
				selectCoverType: null,
			}
		},
		onLoad({
			id
		}) {
			this.id = Number(id)
			this.getData()
			uni.$on('editCover', this.handleCoverCtn)
		},
		computed: {
			// 封面内容类型
			coverCtnType() {
				if (!this.selectCoverType?.covers_all || !this.selectCoverType.covers_all?.length)
					return 0
				return Number(this.selectCoverType.covers_all.find(item => item.id === this.printForm.coverContent).config)
			},
		},
		methods: {
			async getData() {
				try {
					this.$showLoading()
					// 单一文件详细
					const fileInfo = await PrintApi.getCartList({
						id: this.id
					})
					// 总价
					this.totalPrice = fileInfo.allprice
					// 文件详情
					this.fileInfo = fileInfo.result[0]
					// 表单
					this.printForm = JSON.parse(fileInfo.result[0].doc_json).data[0]
					// 初始化范围
					this.printForm.maxPage = Number(this.printForm.maxPage)
					this.initPageRange(this.printForm.maxPage)
					// 设置默认页码选择
					const pageRangeArr = this.printForm.pageRange.split('-')
					this.defaultPageRange = [(pageRangeArr[0] - 1), (pageRangeArr[1] - 1)]
					// 纸张尺寸
					const paperSize = await PrintApi.getPaperSizeList({
						size: 1000,
						p: 1
					})
					this.paperSize = paperSize.result.rows
					// 装订方式列表
					const bindingList = await PrintApi.getBindingList({
						size: 1000,
						p: 1
					})
					this.bindingList = bindingList.result.rows
					// 初始化封面类型
					this.coverTypeList = this.bindingList.find(item => item.id == Number(this.printForm.binding)).covers_all
					// 初始化选中
					if (this.coverTypeList.length && this.printForm.cover) {
						this.selectCoverType = this.coverTypeList.find(item => item.id == this.printForm.cover) || {}
					}
					uni.hideLoading()
				} catch (err) {
					console.log('getData= ', err);
					uni.hideLoading()
				}
			},
			/**
			 * 初始化页码范围
			 * @param {Number} pageNum 最大页码
			 */
			initPageRange(maxNum) {
				let pageArr = []
				for (let i = 1; i <= maxNum; i++) {
					pageArr.push(i)
				}
				this.pageRangeArr = [pageArr, pageArr]
			},
			handlePreview() {
				previewFile(this.printForm.file)
			},
			/**
			 * 处理封面内容
			 */
			handleCoverCtn(data) {
				console.log('handleCoverCtn= ', data);
				if (data.text) this.printForm.coverContentText = data.text
				this.printForm.coverContentImage = BASE_URL + data.path.slice(1)
				this.getPrice()
			},
			/**
			 * 获取价格
			 * @param {String} param 参数名
			 * @param {any} value 值 
			 */
			async getPrice(param, value) {
				try {
					let form = JSON.parse(JSON.stringify(this.printForm))
					let coverTypeList = []
					let selectCoverType = {}
					switch (param) {
						case 'pageRange':
							form.pageRange = [(value.detail.value[0] + 1), (value.detail.value[1] + 1)].join('-')
							break;
						case 'binding':
							form['binding'] = value
							// 支持的封面类型
							coverTypeList = this.bindingList.find(item => item.id == Number(form['binding']))?.covers_all
							if (!coverTypeList.length)
								break;
							selectCoverType = coverTypeList[0]
							// 设置默认封面类型
							form.cover = selectCoverType.id
							// 设置默认封面颜色
							if (selectCoverType?.color) form.coverColor = selectCoverType?.colors_all[0].id || 0
							// 设置默认封面内容ID
							if (selectCoverType?.cover) form.coverContent = selectCoverType?.covers_all[0].id || 0
							break;
						case 'cover':
							form['cover'] = value
							selectCoverType = this.coverTypeList.find(item => item.id == form['cover']) || {}
							// 设置默认封面颜色
							if (selectCoverType?.color) form.coverColor = selectCoverType.colors_all[0].id
							// 设置默认封面内容ID
							if (selectCoverType?.cover) form.coverContent = selectCoverType.covers_all[0].id
							break;
						case 'pageRange':
							if (this.printForm.maxPage === 1)
								throw new Error('当前文档只有一页不可选择范围')
							form.pageRange = `${this.defaultPageRange[0] + 1}-${this.defaultPageRange[1] + 1}`
							break;
						case 'num':
							form[param] = value.value
							break;
						default:
							form[param] = value
							break;
					}
					const res = await PrintApi.getPrintDocPrice({
						data: [form]
					})
					if (param === 'coverContent' && value !== this.printForm.coverContent) {
						form.coverContentImage = ''
						form.coverContentText = ''
					}
					// 重置表单
					// 可以获取价格再更新表单数据
					this.printForm = form
					if (param === 'binding') this.coverTypeList = coverTypeList // 封面分类列表
					if (param === 'cover' || param === 'binding') this.selectCoverType = selectCoverType // 选中的封面分类
					this.totalPrice = res.result.totalAmount
					console.log('getPrice success=', res);
				} catch (err) {
					console.log('getPrice err=', err);
					this.$showToast(err?.message || err, 2500)
				}
			},
			// 提交更改
			async handleSubmit() {
				try {
					this.$showLoading()
					if (this.printForm.coverContent) {
						const selectedCoverCtn = this.selectCoverType.covers_all
							.find(item => item.id == this.printForm.coverContent)
						if (
							(selectedCoverCtn.config == 2 && !this.printForm.coverContentText) ||
							((selectedCoverCtn.config == 3 || selectedCoverCtn.config == 4) && !this.printForm.coverContentImage)
						)
							throw new Error('请先上传封面')
					}
					const res = await PrintApi.UpdateCart({
						cart_id: this.id,
						type: 1,
						doc_json: JSON.stringify({
							user_id: this.$store.getters['userInfo'].user_id,
							data: [this.printForm]
						})
					})
					uni.hideLoading()
					this.$showToast(res.msg)
					uni.navigateBack()
				} catch (err) {
					console.log('handleSubmit err= ', err.message);
					uni.hideLoading()
					this.$showToast(err?.msg || err?.message)
				}
			},
		}
	}
</script>

<style>
	page {
		background-color: #f8f8f8;
	}
</style>
<style lang="scss" scoped>
	::v-deep .u-icon__icon {
		font-size: 26rpx !important;
	}

	.container {
		padding-bottom: 142rpx;
		padding-bottom: calc(142rpx + constant(safe-area-inset-bottom));
		padding-bottom: calc(142rpx + env(safe-area-inset-bottom));

		--common-font-size: 28rpx;
	}

	.main {
		margin: 30rpx;
		padding: 30rpx;
		border-radius: 10rpx;
		background: #ffffff;
		box-shadow: 0 16rpx 40rpx 0 #00000008;
	}

	// 文件信息
	.file-info {
		display: flex;
		align-items: center;
		margin-bottom: 35rpx;
	}

	.file-img {
		width: 44rpx;
		height: 44rpx;
	}

	.file-txt {
		flex: 1;
		margin-left: 10rpx;
		color: #000000;
		font-size: 28rpx;
	}

	// 选择项
	.item {
		display: flex;
		padding: 30rpx 0;
		border-top: 2rpx solid #f3f3f3;
	}

	.item-left {
		display: flex;
		margin-top: 10rpx;
		color: #909090;
		font-size: 28rpx;
	}

	.item-right {
		flex: 1;
		display: flex;
		justify-content: flex-end;
		flex-wrap: wrap;
		margin-left: 30rpx;
		gap: 20rpx;
	}

	.item-action {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 10rpx 20rpx;
		border-radius: 10rpx;
		border: 2rpx solid #d6d6d6;
		background: #ffffff;
		color: #989898;
		font-size: var(--common-font-size);
		transition: all 0.3s;

		&__active {
			border: 2rpx solid $theme-color;
			background: #fff6ee;
			color: $theme-color;
		}
	}


	.action-color-box {
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 10rpx;
		border: 2rpx solid transparent;
		background: transparent;
		padding: 6rpx;

		&__active {
			border: 2rpx solid #ff9c24;
			background: #fff6ee;
		}
	}

	.item-action-color {
		box-sizing: border-box;
		position: relative;
		padding: 10rpx 32rpx;
		color: #ffffff;
		text-align: center;
		font-size: var(--common-font-size);
		background: #fff;
		border-radius: 10rpx;

		&__white {
			border: 2rpx solid #b6b6b6;
			color: #5b5b5b;
		}
	}

	// 底部
	.footer {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx 20rpx 30rpx 40rpx;
		padding-bottom: calc(30rpx + constant(safe-area-inset-bottom));
		padding-bottom: calc(30rpx + env(safe-area-inset-bottom));
		border-top: 2rpx solid #f4f4f4;
		background: #ffffff;
		z-index: 999;
	}

	.price {
		font-size: var(--common-font-size);
		color: #474747;

		span {
			color: $theme-color;
		}

		.price-num {
			font-size: 36rpx;
		}
	}

	.actions {
		display: flex;

		view {
			box-sizing: border-box;
			padding: 12rpx 60rpx;
			border-radius: 10rpx;
			font-size: var(--common-font-size);
			text-align: center;
		}

		.preview {
			border: 2rpx solid #aaaaaa;
			color: #aaaaaa;
		}

		.confirm {
			margin-left: 20rpx;
			background: $gradient-bg-color;
			color: #FFFFFF;
		}
	}
</style>